package GEMonitor;

import java.util.List;

import GEMonitor.em.MsgType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;

public class GEMsgDecoderClient extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if(!in.isReadable())
        {
            return;
        }
        
        byte soh = in.readByte();
        if(soh != 0x01)
        {
            return;
        }

        int length =  Integer.parseInt(in.readCharSequence(4, CharsetUtil.US_ASCII).toString(),16);
        if(length<8)
        {
            return;
        }

        String msg_type = in.readCharSequence(2, CharsetUtil.US_ASCII).toString();

        String systemID="";
        if(msg_type.equals("S0"))
        {
            systemID =  in.readCharSequence(12, CharsetUtil.US_ASCII).toString();
        }

        int content_len = length - 10 - systemID.length();
        byte[] content = new byte[content_len];
        if(content_len > 0)
        {
            in.readBytes(content);
        }

        //todo 加密
        if(msg_type.equals(MsgType.REPORT_ENCRYPTED.getValue())){
            content = AesUtil.aesEncode(content);
            content_len = content.length;
        }

        String check = in.readCharSequence(2, CharsetUtil.US_ASCII).toString();

        byte[] arr = new byte[length-8];
        System.arraycopy(msg_type.getBytes(), 0, arr, 0, msg_type.length());
        if(systemID.length()>0)
        {
            System.arraycopy(systemID.getBytes(), 0, arr, 2, systemID.length());
        }
        if(content.length > 0)
        {
            System.arraycopy(content, 0, arr, msg_type.length()+systemID.length(), content_len);
        }

        if(!Helper.checksum(arr).equals(check))
        {
            return;
        }

        byte etx = in.readByte();
        if(etx != 0x03)
        {
            return;
        }

        GEMsg msg = new GEMsg();
        msg.msg_type = msg_type;
        msg.systemID = systemID;
        msg.content = content;
        
        out.add(msg);
    }
}